package com.movecar.ui;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import BLLocationCallbacker.DialogItemSelectCallbacker;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.movecar.R;
import com.movecar.adapter.MyShareGridViewAdapter;
import com.movecar.dialog.MoveCarDialogBuilder;
import com.movecar.model.CloudBeansBean;
import com.movecar.pic.Bimp;
import com.movecar.pic.TestPicActivity;
import com.movecar.utils.Alert;
import com.movecar.utils.AppConfig;
import com.movecar.utils.BitMapUtil;
import com.movecar.utils.DataStore;
import com.movecar.utils.FileProvider;
import com.movecar.utils.HttpPostRequestAsyncTask;
import com.movecar.utils.PopupWindowAnimation;
import com.movecar.utils.RequestResultCallback;
import com.movecar.widget.CustomProgressDialog;
import com.movecar.widget.MyGridView;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 我的-吐槽
 * 
 * @author Zhao.JQ
 * 
 */

public class MoreSuggestionActivity extends Activity implements android.view.View.OnClickListener,
		DialogItemSelectCallbacker {

	private EditText suggestion_info;
	private String upLoadPic;
	private StringBuffer uploadPath = new StringBuffer();
	private InputMethodManager imm;
	private Button ok, back, camera, album;
	private CustomProgressDialog progressDialog = null;
	private MyGridView mGrideView;// 添加照片
	private MyShareGridViewAdapter mGridViewAdapter;
	private AlertDialog mDialogChoose;
	final List<String> pathList = new ArrayList<String>();
	private ArrayList<Bitmap> bitmapList = new ArrayList<Bitmap>();
	private List<Bitmap> upLoadPicList = new ArrayList<Bitmap>();
	private ArrayList<String> dataList = new ArrayList<String>();
	private TextView chCounterText;

	private RelativeLayout suggestion_info_relative;

	private CloudBeansBean mCloudBeansBean;
	/* 确定删除图片的标记 */
	private int delNum;
	/* 确定删除图片 */
	private static final int YES = -1;
	/* 取消删除图片 */
	private static final int NO = -2;
	/* 选择图片 */
	private static final int PICK = 0x11;

	/** 新相片文件 */
	private File rFilePicture = null;
	/** 相片临时文件 */
	private File rFileTemporary = null;
	private final ArrayList<String> mListImageFile = new ArrayList<String>();
	private ImageLoader imageLoader = null;
	private View mainView;
	private LayoutInflater layoutInflater;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);mainView = layoutInflater.inflate(R.layout.more_suggestion, null);
		setContentView(mainView);
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		initView();
	}

	private void initView() {
		imageLoader = ImageLoader.getInstance();

		suggestion_info_relative = (RelativeLayout) findViewById(R.id.suggestion_info_relative);

		chCounterText = (TextView) findViewById(R.id.text_count);
		back = (Button) findViewById(R.id.btn_left);
		back.setVisibility(View.VISIBLE);
		back.setOnClickListener(this);
		ok = (Button) findViewById(R.id.ok);
		ok.setOnClickListener(this);
		camera = (Button) findViewById(R.id.camera);
		camera.setOnClickListener(this);
		album = (Button) findViewById(R.id.album);
		album.setOnClickListener(this);
		TextView title = (TextView) findViewById(R.id.title);
		title.setText("吐槽");

		suggestion_info = (EditText) findViewById(R.id.suggestion_info);
		suggestion_info.setOnClickListener(this);
		suggestion_info.addTextChangedListener(new TextWatcher() {
			@Override
			public void afterTextChanged(Editable s) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				String content = suggestion_info.getText().toString();
				if (content.length() > 300) {
					chCounterText.setTextColor(Color.RED);
				} else {
					chCounterText.setTextColor(R.color.text_black1);
				}
				chCounterText.setText(content.length() + "/" + "300");
			}

		});
		mGrideView = (MyGridView) findViewById(R.id.edit_photo_grid);
		mGrideView.setSelector(new ColorDrawable(Color.TRANSPARENT));

		mGridViewAdapter = new MyShareGridViewAdapter(this, new ArrayList<Bitmap>());
		if (dataList.size() == 0) {
			mGrideView.setVisibility(View.GONE);
		}
		mGrideView.setAdapter(mGridViewAdapter);
		// 添加删除图片监听
		mGrideView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(final AdapterView<?> arg0, final View arg1, final int arg2, final long arg3) {
				delNum = arg2;
				(mDialogChoose = MoveCarDialogBuilder.buildDialog(MoreSuggestionActivity.this, "是否删除图片",
						MoreSuggestionActivity.this)).show();
			}
		});

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_left:

			imm.hideSoftInputFromWindow(suggestion_info.getWindowToken(), 0);
			finish();

			break;

		case R.id.camera:
			if (upLoadPicList.size() >= 8) {
				Alert.warn(this, "只能上传8张照片");
				return;
			}
			try {

				rFilePicture = FileProvider.getNewJpegFile();
				final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(rFilePicture));
				// 获得SharedPreferences对象
				SharedPreferences preferences = getSharedPreferences("URI", 0);
				// 获得可编辑对象
				SharedPreferences.Editor editor = preferences.edit();
				editor.putString("uri", Uri.fromFile(rFilePicture).toString());
				editor.commit();
				intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
				intent.putExtra("return-data", true);
				startActivityForResult(intent, MoreSuggestionActivity.PICK);
			} catch (final IOException e) {
				Toast.makeText(this, "无法完成拍照操作，请检查存储卡是否安装或空间已满。", Toast.LENGTH_SHORT).show();
				rFilePicture = null;
			}
			break;
		case R.id.album:
			if (upLoadPicList.size() >= 6) {
				Alert.warn(this, "只能上传8张照片");
				return;
			}
			Intent intent = new Intent(MoreSuggestionActivity.this, TestPicActivity.class);
			Bundle bundle = new Bundle();
			bundle.putStringArrayList("dataList", getIntentArrayList(dataList));
			intent.putExtras(bundle);
			startActivityForResult(intent, 0);
			break;

		case R.id.suggestion_info:

			break;
		case R.id.ok:
			if (!TextUtils.isEmpty(suggestion_info.getText().toString())) {
				startProgressDialog();
				if (upLoadPicList.size() == 0) {
					uploadInfo("");
				} else {
					for (int i = 1; i <= upLoadPicList.size(); i++) {
						// 压缩图片上传
						ByteArrayOutputStream myStream = new ByteArrayOutputStream();
						upLoadPicList.get(i - 1).compress(Bitmap.CompressFormat.JPEG, 60, myStream);
						byte[] myCopybyte = myStream.toByteArray();
						int myLength = myCopybyte.length;
						upLoadPic = Base64.encodeToString(myCopybyte, 0, myLength, Base64.DEFAULT);
						uploadPath.append(upLoadPic);
						uploadPath.append(", ");

						uploadInfo(uploadPath.toString());
					}
				}

			} else {
				Alert.error(MoreSuggestionActivity.this, "请填写吐槽内容!");
			}

			break;

		default:
			break;
		}

	}

	/**
	 * 上传吐槽内容及图片
	 * 
	 * @author Zhao.JQ
	 */
	@SuppressWarnings("unchecked")
	private void uploadInfo(String uploadPath) {

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "submitAdviseNew1"));
		// 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("content", suggestion_info.getText().toString().trim()));
		params.add(new BasicNameValuePair("picList", uploadPath.toString()));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				stopProgressDialog();
				String result = (String) object;
				Gson gson = new Gson();
				try {
					mCloudBeansBean = gson.fromJson(result, CloudBeansBean.class);
				} catch (Exception e) {
					return;
				}
				if (mCloudBeansBean != null) {
					if ("0".equals(mCloudBeansBean.getResultCode())) {
						if (!TextUtils.isEmpty(mCloudBeansBean.getCoinAlert())) {
							new PopupWindowAnimation(mainView, MoreSuggestionActivity.this);
						}
						Alert.info(MoreSuggestionActivity.this, "吐槽成功");
						finish();
					}

				} else {
					stopProgressDialog();
					Alert.error(MoreSuggestionActivity.this, result);
				}
			}

			@Override
			public void onFail(String exception) {
				stopProgressDialog();
				Alert.warn(MoreSuggestionActivity.this, "与服务器连接失败，请检查网络");

			}
		}, DataStore.class, AppConfig.USER).execute(params);
	}

	private ArrayList<String> getIntentArrayList(ArrayList<String> dataList) {
		pathList.clear();
		for (Bitmap b : this.bitmapList) {
			Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), b, null, null));
			File f = FileProvider.getFileByUri(this, uri);
			pathList.add(f.getPath());
		}
		dataList.clear();
		dataList.addAll(pathList);
		return dataList;

	}

	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(this);
			progressDialog.setMessage("正在加载...");
		}

		progressDialog.show();
	}

	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onActivityResult(int, int,
	 * android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == MoreSuggestionActivity.PICK) {
			if (resultCode != Activity.RESULT_OK) {
				rFilePicture = null;
				return;
			}

			/* rFilePicture值为null表明是从相册挑选。 */
			if (rFilePicture == null) {
				if (null == data) {
					// 读取数据
					SharedPreferences preferences = getSharedPreferences("URI", 0);

					rFilePicture = FileProvider.getFileByUri(this, Uri.parse(preferences.getString("uri", "")));

				} else {
					rFilePicture = FileProvider.getFileByUri(this, data.getData());
				}

			}
			mListImageFile.add(rFilePicture.getPath());
			List<Bitmap> bpList = new ArrayList<Bitmap>();
			try {
				Bitmap bitmap = ThumbnailUtils.extractThumbnail(Bimp.revitionImageSize(mListImageFile.get(0)), 240,
						240, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
				int pictureDegree = BitMapUtil.readPictureDegree(mListImageFile.get(0));
				bitmapList.add(BitMapUtil.rotaingImageView(pictureDegree, bitmap));

				bpList.add(BitMapUtil.rotaingImageView(pictureDegree,
						BitMapUtil.getBitmapFromFile(rFilePicture, 1280, 1280)));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			mGrideView.setVisibility(View.VISIBLE);
			mGridViewAdapter.setBitmapList(bitmapList);
			upLoadPicList.clear();
			upLoadPicList.addAll(bpList);
			mGridViewAdapter.notifyDataSetChanged();
			rFileTemporary = null;
			mListImageFile.clear();

			rFilePicture = null;
			SharedPreferences preferences = getSharedPreferences("URI", 0);
			// 获得可编辑对象
			SharedPreferences.Editor editor = preferences.edit();
			editor.clear();
		} else if (requestCode == 0) {
			if (resultCode == RESULT_OK) {

				Bundle bundle = data.getExtras();
				ArrayList<String> tDataList = Bimp.drr;
				if (tDataList != null && tDataList.size() > 0) {
					mGrideView.setVisibility(View.VISIBLE);
					dataList.clear();
					dataList.addAll(tDataList);
					this.bitmapList.clear();
					upLoadPicList.clear();
					List<Bitmap> bpList = new ArrayList<Bitmap>();
					for (String path : dataList) {
						File file = new File(path);

						// TODO 内存溢出
						Bitmap bitmap = ThumbnailUtils.extractThumbnail(BitMapUtil.getSuitableBitmap(file), 240, 240,
								ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
						int pictureDegree = BitMapUtil.readPictureDegree(file.getPath());
						this.bitmapList.add(BitMapUtil.rotaingImageView(pictureDegree, bitmap));

						bpList.add(BitMapUtil.rotaingImageView(pictureDegree,
								BitMapUtil.comp(BitMapUtil.getBitmapFromFile(file, 1280, 1280))));

					}

					upLoadPicList.addAll(bpList);
					mGridViewAdapter.setBitmapList(this.bitmapList);
					mGridViewAdapter.notifyDataSetChanged();
				}
			}
		} else if (requestCode == 2) {
			if (resultCode == RESULT_OK) {
				setResult(RESULT_OK);
				finish();
			}
		}
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		if (dialog == mDialogChoose) {
			if (which == YES) {
				this.bitmapList.remove(delNum);
				upLoadPicList.remove(delNum);
				mGridViewAdapter.notifyDataSetChanged();

			} else if (which == NO) {
				return;
			}
		}

	}

}
